import { Utils } from "../utils";

export class Block {
 
  private index: number = 0;//区块链索引
  private timeStamp: number = 0;  //时间戳
  private blockData: string ="";  //数据
  private previousHash: string;  //上一级区块链
  private randomStr: string;  //随机值
  private hash: string;  //当前区块链


  /**
   * 获取区块索引值
   */
 public getIndex()
 {
     return  this.index;
 }

 /**
  * 获取区块
  */
 public getHash()
 {
     return  this.hash;
 }


  /**
   * Constructor
   *
   * @class Block
   * @constructor
   */
  constructor(index:number,timeStamp:number,blockData:any,randomStr:string,previousHash:string) { 
      this.index=index;  
      this.timeStamp=timeStamp; 
      if(typeof(blockData)=="string")
      {
         this.blockData=Utils.encoding64(blockData);  
      }
      else{
        let blockStr = JSON.stringify(blockData);
        this.blockData=Utils.encoding64(blockStr);
      }
      this.previousHash=previousHash;  
      this.randomStr=randomStr;  
      this.hash=this.hash_block();  
  }
 
  private hash_block() {
    let str = this.index + this.timeStamp + this.blockData + this.randomStr + this.previousHash;
    return Utils.sha256(str);
  }

}